package com.java.simple.study.juc.p3.reentrant;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhoujl
 * @date 2022/5/11 20:30
 * @desc
 */
@Slf4j(topic = "c.TestCondition")
public class TestCondition {

    static final ReentrantLock lock = new ReentrantLock();
    static Condition waitCigaretteQueue = lock.newCondition();
    static Condition waitBreakfastQueue = lock.newCondition();
    static volatile boolean hasCigarette = false;
    static volatile boolean hasBreakfast = false;

    public static void main(String[] args) {
        new Thread(() -> {
            lock.lock();
            try {
                while (!hasCigarette) {
                    try {
                        waitCigaretteQueue.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        log.debug("等烟过程中被打断");
                        return;
                    }
                }
                log.debug("等到烟了,开始干活了。。。");
            } finally {
                lock.unlock();
            }
        }, "小南").start();

        new Thread(() -> {
            lock.lock();
            try {
                while (!hasBreakfast) {
                    try {
                        waitBreakfastQueue.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        log.debug("等早餐过程中被打断");
                        return;
                    }
                }
                log.debug("等到早餐了,开始干活了。。。");
            } finally {
                lock.unlock();
            }
        }, "小女").start();

        Sleeper.sleep(2);
        sendCigarette();
        Sleeper.sleep(2);
        sendBreakfast();
    }

    private static void sendCigarette() {
        lock.lock();
        try {
            log.debug("送烟到【烟等待室】了");
            hasCigarette = true;
            waitCigaretteQueue.signal();
        } finally {
            lock.unlock();
        }
    }

    private static void sendBreakfast() {
        lock.lock();
        try {
            log.debug("送早餐到【早餐等待室】了");
            hasBreakfast = true;
            waitBreakfastQueue.signal();
        } finally {
            lock.unlock();
        }
    }

}
